package com.xnyzc.lhy.mis.service.impl.cms.util;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.dept.EOffIceType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.service.cms.util.IOfficeUtilService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 部门工具
 * @Author zhuyubin
 * @Date 2019-08-26 14:00
 **/
@Service
public class OfficeUtilServiceImpl implements IOfficeUtilService {

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    /**
     * 根据部门id查询上级公司
     *
     * @param officeId 部门id
     * @return
     */
    @Override
    public Long getCompanyId(Long officeId) {
        OaSysOffice oaSysOffice = oaSysOfficeMapper.selectById(officeId);
        String parentIds = oaSysOffice.getParentIds();
        if (parentIds.contains(",")) {
            String[] officeParentIds = parentIds.split(",");
            List<OaSysOffice> oaSysOffices = oaSysOfficeMapper.selectList(Wrappers.<OaSysOffice>lambdaQuery().in(OaSysOffice::getOfficeId, officeParentIds));
            if (CheckUtil.objIsNotEmpty(oaSysOffices)) {
                for (int i = oaSysOffices.size() - 1; i >= 0; i--) {
                    if (EOffIceType.company.getValue().equals(Integer.valueOf(oaSysOffices.get(i).getType()))) {
                        return oaSysOffices.get(i).getOfficeId();
                    }
                }
            }
        }
        return null;
    }

    @Override
    public Long getOfficeParentId(Long officeId) {
        OaSysOffice oaSysOffice = oaSysOfficeMapper.selectById(officeId);
        if (CheckUtil.strIsEmpty(oaSysOffice.getParentId())) {
            throw PangException.create(EErrorCode.noData);
        }
        return Long.valueOf(oaSysOffice.getParentId());
    }
}
